﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace BoxSauce.AgencyToolkit.Extensions
{
    /// <summary>
    /// Enumerable Extensions class
    /// </summary>
    public static class EnumerableExtensions
    {
        /// <summary>
        /// Gets a random element of an Enumerable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumerable"></param>
        /// <returns>Random element</returns>
        public static T RandomElement<T>(this IEnumerable<T> enumerable)
        {
            if (enumerable == null)
                throw new ArgumentNullException("enumerable");

            return enumerable.RandomElement(new Random());
        }

        /// <summary>
        /// Gets a random element of an Enumerable using the Random class passed in
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumerable"></param>
        /// <param name="rand"></param>
        /// <returns>Random element from enumerable</returns>
        public static T RandomElement<T>(this IEnumerable<T> enumerable, Random rand)
        {
            if (enumerable == null)
                throw new ArgumentNullException("enumerable");

            var list = enumerable.ToList();
            if (!list.Any())
                throw new ArgumentException("The enumerable is empty.");

            var index = rand.Next(0, list.Count());
            return list.ElementAt(index);
        }
    }
}
